package com.esfak47.mediafetcher.plugin.pornhub.service.impl;

import com.esfak47.common.utils.StringUtils;
import com.esfak47.mediafetcher.core.domain.FetchAble;
import com.esfak47.mediafetcher.core.domain.Media;
import com.esfak47.mediafetcher.core.service.CrawlerService;
import com.esfak47.mediafetcher.plugin.pornhub.dto.pornhub.MediaDefinitions;
import com.esfak47.mediafetcher.plugin.pornhub.dto.pornhub.PornhubInnerObject;
import com.google.gson.Gson;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;

/**
 * @author tony
 * @date 2018/5/19
 */
public class JsoupPornHubCrawlerService implements CrawlerService {

    @Override
    public Optional<Media> getVideoExtInfo(FetchAble fetchAble) {

        String location = fetchAble.getLocation();
        if (StringUtils.isBlank(location)) {
            return Optional.empty();
        }
        try {
            Document doc = Jsoup.parse(new URL(fetchAble.getLocation()), 10000);
            Element script = doc.selectFirst("#player script");
            final String data = script.data();
            final String substring = data.substring(data.indexOf("{"), data.indexOf(";"));
            Gson gson = new Gson();
            Element viewCountElement = doc.selectFirst(".rating-info-container .count");
            final Integer integer = Integer.valueOf(viewCountElement.html().replace(",", ""));
            final PornhubInnerObject pornhubInnerObject = gson.fromJson(substring, PornhubInnerObject.class);
            final List<MediaDefinitions> mediaDefinitions = pornhubInnerObject.getMediaDefinitions();
            final Optional<MediaDefinitions> first = mediaDefinitions.stream().findFirst();
            final MediaDefinitions definitions = first.get();

            final String video_title = pornhubInnerObject.getVideo_title();
            Media media = Media.builder().duration(Integer.valueOf(pornhubInnerObject.getVideo_duration()))
                .extractorKey("pornhub")
                .title(video_title)
                .ext("mp4")
                .fullTitle(video_title)
                .fileName(video_title + ".mp4")
                .hd("1".equals(pornhubInnerObject.getIsHD()))
                .webpageUrl(fetchAble.getLocation())
                .url(definitions.getVideoUrl())
                .id(script.parent().attr("data-video-id"))
                .viewCount(integer)
                .thumbnail(pornhubInnerObject.getImage_url())
                .build();
            return Optional.of(media);

        } catch (IOException e) {
            return Optional.empty();
        }

    }
}
